<template>
  <div class="space-y-6">
    <!-- 输入方式选择 -->
    <div class="flex items-center justify-center space-x-4 p-4 bg-gray-50 rounded-lg">
      <button
        type="button"
        @click="inputMethod = 'text'"
        class="flex-1 py-3 px-4 rounded-lg font-medium transition-all"
        :class="
          inputMethod === 'text'
            ? 'bg-blue-500 text-white shadow-md'
            : 'bg-white text-gray-700 hover:bg-gray-100'
        "
      >
        <Edit3 class="w-5 h-5 inline mr-2" />
        手动输入
      </button>
      <button
        type="button"
        @click="inputMethod = 'image'"
        class="flex-1 py-3 px-4 rounded-lg font-medium transition-all"
        :class="
          inputMethod === 'image'
            ? 'bg-blue-500 text-white shadow-md'
            : 'bg-white text-gray-700 hover:bg-gray-100'
        "
      >
        <Image class="w-5 h-5 inline mr-2" />
        图片识别
      </button>
    </div>

    <!-- 学段选择 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-2">
        <GraduationCap class="inline w-4 h-4 mr-1" />
        选择学段
      </label>
      <div class="grid grid-cols-3 gap-3">
        <button
          v-for="level in gradeLevels"
          :key="level.value"
          type="button"
          @click="formData.gradeLevel = level.value"
          class="py-3 px-4 rounded-lg font-medium transition-all"
          :class="
            formData.gradeLevel === level.value
              ? 'bg-blue-500 text-white shadow-md'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          "
        >
          {{ level.label }}
        </button>
      </div>
      <p v-if="errors.gradeLevel" class="mt-1 text-sm text-red-400">
        {{ errors.gradeLevel }}
      </p>
    </div>

    <!-- 图片上传（图片识别模式） -->
    <div v-if="inputMethod === 'image'">
      <ImageUpload
        ref="imageUploadRef"
        @ocr-complete="handleOCRComplete"
        @ocr-error="handleOCRError"
      />
    </div>

    <!-- 文本输入（手动输入模式或OCR完成后） -->
    <div v-if="inputMethod === 'text' || ocrCompleted">
      <!-- 作文标题 -->
      <div>
        <label for="title" class="block text-sm font-medium text-gray-700 mb-2">
          作文标题（可选）
        </label>
        <input
          id="title"
          v-model="formData.title"
          type="text"
          placeholder="请输入作文标题"
          class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
          maxlength="100"
        />
      </div>

      <!-- 作文正文 -->
      <div>
        <label for="content" class="block text-sm font-medium text-gray-700 mb-2">
          作文内容
        </label>
        <textarea
          id="content"
          v-model="formData.content"
          placeholder="请将作文内容粘贴或输入到这里..."
          rows="12"
          class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-y"
          :class="{ 'border-red-400': errors.content }"
          @input="debouncedValidateContent"
        ></textarea>
        
        <!-- 字数统计 -->
        <div class="flex items-center justify-between mt-2">
          <p v-if="errors.content" class="text-sm text-red-400">
            {{ errors.content }}
          </p>
          <p v-else class="text-sm text-gray-500">
            {{ contentLength }} / 5000 字
            <span v-if="contentLength < 50" class="text-red-400">
              （至少需要 50 字）
            </span>
            <span v-else-if="contentLength >= 50 && contentLength <= 5000" class="text-green-500">
              ✓
            </span>
          </p>
        </div>
      </div>

      <!-- 高级设置（可折叠） -->
      <div class="border border-gray-200 rounded-lg">
        <button
          type="button"
          @click="showAdvanced = !showAdvanced"
          class="w-full flex items-center justify-between p-4 hover:bg-gray-50 transition-colors"
        >
          <span class="font-medium text-gray-700">高级设置（可选）</span>
          <ChevronDown
            class="w-5 h-5 text-gray-400 transition-transform"
            :class="{ 'rotate-180': showAdvanced }"
          />
        </button>
        
        <div v-show="showAdvanced" class="p-4 pt-0 space-y-4 border-t border-gray-200">
          <!-- 批改风格 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-3">
              批改风格
            </label>
            <div class="space-y-2">
              <label
                v-for="style in correctionStyles"
                :key="style.value"
                class="flex items-center space-x-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors"
                :class="{ 'border-blue-500 bg-blue-50': formData.style === style.value }"
              >
                <input
                  v-model="formData.style"
                  type="radio"
                  :value="style.value"
                  class="w-4 h-4 text-blue-500"
                />
                <div>
                  <p class="font-medium text-gray-800">{{ style.label }}</p>
                  <p class="text-sm text-gray-500">{{ style.desc }}</p>
                </div>
              </label>
            </div>
          </div>

          <!-- 批改重点 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-3">
              批改重点（可多选）
            </label>
            <div class="space-y-2">
              <label
                v-for="focus in correctionFocus"
                :key="focus.value"
                class="flex items-center space-x-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors"
                :class="{ 'border-blue-500 bg-blue-50': formData.focus.includes(focus.value) }"
              >
                <input
                  v-model="formData.focus"
                  type="checkbox"
                  :value="focus.value"
                  class="w-4 h-4 text-blue-500 rounded"
                />
                <span class="text-gray-800">{{ focus.label }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <button
      type="button"
      @click="handleSubmit"
      :disabled="!canSubmit || loading"
      class="w-full py-4 px-6 rounded-lg font-medium text-white transition-all text-lg"
      :class="
        !canSubmit || loading
          ? 'bg-gray-300 cursor-not-allowed'
          : 'bg-blue-500 hover:bg-blue-600 shadow-md hover:shadow-lg'
      "
    >
      <span v-if="loading" class="flex items-center justify-center">
        <Loader class="w-5 h-5 mr-2 animate-spin" />
        提交中...
      </span>
      <span v-else>
        <Send class="w-5 h-5 inline mr-2" />
        提交批改
      </span>
    </button>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { Edit3, Image, GraduationCap, ChevronDown, Loader, Send } from 'lucide-vue-next';
import ImageUpload from './ImageUpload.vue';
import { debounce } from '@/utils/performance';

const props = defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['submit']);

// 引用
const imageUploadRef = ref(null);

// 输入方式
const inputMethod = ref('text'); // 'text' or 'image'
const ocrCompleted = ref(false);

// 高级设置展开状态
const showAdvanced = ref(false);

// 表单数据
const formData = reactive({
  title: props.initialData.title || '',
  content: props.initialData.content || '',
  gradeLevel: props.initialData.gradeLevel || 'middle',
  style: 'standard', // encourage/standard/strict
  focus: [], // structure/language/idea
});

// 表单验证错误
const errors = reactive({
  gradeLevel: '',
  content: '',
});

// 学段选项
const gradeLevels = [
  { value: 'primary', label: '小学' },
  { value: 'middle', label: '初中' },
  { value: 'high', label: '高中' },
];

// 批改风格选项
const correctionStyles = [
  { value: 'encourage', label: '鼓励式', desc: '注重鼓励和表扬，温和指出问题' },
  { value: 'standard', label: '标准式', desc: '平衡表扬和批评，客观评价' },
  { value: 'strict', label: '严格式', desc: '严格要求，详细指出所有问题' },
];

// 批改重点选项
const correctionFocus = [
  { value: 'structure', label: '侧重结构' },
  { value: 'language', label: '侧重语言' },
  { value: 'idea', label: '侧重立意' },
];

// 内容长度
const contentLength = computed(() => formData.content.length);

// 是否可以提交
const canSubmit = computed(() => {
  return (
    formData.gradeLevel &&
    formData.content &&
    formData.content.length >= 50 &&
    formData.content.length <= 5000
  );
});

/**
 * 验证内容（立即执行）
 */
const validateContent = () => {
  errors.content = '';
  
  if (!formData.content) {
    errors.content = '请输入作文内容';
  } else if (formData.content.length < 50) {
    errors.content = '作文内容至少需要 50 个字符';
  } else if (formData.content.length > 5000) {
    errors.content = '作文内容不能超过 5000 个字符';
  }
};

/**
 * 防抖版本的内容验证
 * 用于输入时的实时验证，避免频繁触发
 */
const debouncedValidateContent = debounce(validateContent, 300);

/**
 * 处理OCR完成
 */
const handleOCRComplete = (text) => {
  formData.content = text;
  ocrCompleted.value = true;
  console.log('[EssayForm] OCR completed, text length:', text.length);
};

/**
 * 处理OCR错误
 */
const handleOCRError = (error) => {
  console.error('[EssayForm] OCR error:', error);
  ocrCompleted.value = false;
};

/**
 * 处理提交
 */
const handleSubmit = () => {
  // 验证表单
  validateContent();
  
  if (!canSubmit.value) {
    return;
  }
  
  // 准备提交数据
  const submitData = {
    title: formData.title || '未命名作文',
    content: formData.content,
    gradeLevel: formData.gradeLevel,
    // 高级设置（可选）
    correctionStyle: formData.style,
    correctionFocus: formData.focus,
  };
  
  // 触发提交事件
  emit('submit', submitData);
};

/**
 * 重置表单
 */
const resetForm = () => {
  formData.title = '';
  formData.content = '';
  formData.gradeLevel = 'middle';
  formData.style = 'standard';
  formData.focus = [];
  ocrCompleted.value = false;
  showAdvanced.value = false;
  Object.keys(errors).forEach((key) => {
    errors[key] = '';
  });
  
  // 清除图片上传
  if (imageUploadRef.value) {
    imageUploadRef.value.clearImage();
  }
};

// 暴露方法供父组件调用
defineExpose({
  resetForm,
});
</script>

<style scoped>
/* 无需额外样式，全部使用TailwindCSS */
</style>

